﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Maydew.Windows.Forms.Controls.FlexiCell
{
    /// <summary>
    /// 为单元格提供文本框编辑器。
    /// </summary>
    public class TextCellEditor : CellEditor
    {
        #region " 私有方法 "
        /// <summary>
        /// 文本框编辑控件。
        /// </summary>
        private TextBox _editor = null;
        #endregion

        #region " 构造函数 "
        /// <summary>
        /// 初始化 TextCellEditor 类的新实例。
        /// </summary>
        public TextCellEditor()
        {
            _editor = new TextBox();
            _editor.Multiline = true;
            _editor.BorderStyle = BorderStyle.None;
            Editor = _editor;
        }
        #endregion

        #region " 友元方法 "
        /// <summary>
        /// 设置编辑器值时。
        /// </summary>
        protected override void OnSetEditorValue()
        {
            _editor.Text = string.Format("{0}", Owner.Value);
        }
        /// <summary>
        /// 获取编辑器值时。
        /// </summary>
        protected override void OnGetEditorValue()
        {
            Owner.Value = ConvertValueType(_editor.Text);
        }
        private object ConvertValueType(string s)
        {
            double d;
            if (double.TryParse(s, out d))
            {
                return d;
            }
            DateTime date;
            if (DateTime.TryParse(s, out date))
            {
                return date;
            }
            return s;
        }
        /// <summary>
        /// 显示编辑器时。
        /// </summary>
        protected override void OnShowEditor()
        {
            _editor.Font = Owner.Font;
            //_editor.ForeColor=Owner.
            base.OnShowEditor();
        }
        #endregion

        #region " 绘制方法 "
        /// <summary>
        /// 绘制编辑器。
        /// </summary>
        /// <param name="g">绘图参数。</param>
        public override void Painting(Graphics g)
        {
            Color color = Owner.ForeColor;
            using (Brush brush = new SolidBrush(color))
            {
                Rectangle bound = Owner.Bounds;
                bound.Inflate(-1, -1);
                RectangleF rect = new RectangleF(
                    Convert.ToSingle(bound.Left),
                    Convert.ToSingle(bound.Top),
                    Convert.ToSingle(bound.Width),
                    Convert.ToSingle(bound.Height));
                StringFormat sf = new StringFormat(StringFormat.GenericDefault);
                Shape.ConvertContentAlignment(sf, Owner.TextAlign);

                g.DrawString(Owner.Text, Owner.Font, brush, rect, sf);
            }
        }
        #endregion

        public override object Clone()
        {
            return new TextCellEditor();
        }
    }
}
